import { useState, useEffect, useContext } from "react";
import {
  Box,
  Text,
  Flex,
  IconButton,
  Collapse,
  useToast,
} from "@chakra-ui/react";
import { ChevronDownIcon, ChevronUpIcon } from "@chakra-ui/icons";
import newKeyInfos from "@/src/config/newKeyInfos.json"; // 确保路径正确
import { Keycode, KeyGroup, MouseKey } from "@/src/types/types.v1";
import { MainContext } from "@/src/providers/MainProvider";

interface KeyDataItem extends KeyGroup {
  show: boolean;
}

const MacroKey = () => {
  const {
    connectedMouse,
    mouseKeys,
    setMouseKeys,
    selKeyIndex,
    profile,
    profileIndex,
  } = useContext(MainContext);
  const toast = useToast();
  const [selectedKey, setSelectedKey] = useState<string | null>(null);
  const [keyData, setKeyData] = useState<KeyDataItem[]>([]);

  // 加载新键位信息
  useEffect(() => {
    if (newKeyInfos?.Other?.list) {
      const updatedKeyData = newKeyInfos.Other.list.map(
        (item): KeyDataItem => ({
          ...item,
          show: true,
          keycodes: item.keycodes.map((code) => ({
            ...code,
            //lang: code.lang || ''  // 确保每个 keycode 都有 lang 属性
            lang: "", // 确保每个 keycode 都有 lang 属性
          })),
        })
      );
      setKeyData(updatedKeyData);
    }
  }, []);

  // 处理按键点击
  const handleKeyClick = (
    groupIndex: number,
    keyIndex: number,
    keyName: string
  ) => {
    setSelectedKey(`${groupIndex}-${keyIndex}`);

    if (selKeyIndex >= 0 && mouseKeys[selKeyIndex]) {
      const keyInfo = keyData[groupIndex].keycodes[keyIndex];
      const newKey = {
        ...mouseKeys[selKeyIndex],
        keyName: keyInfo.name,
        type: keyInfo.type || 0x70,
        code1: keyInfo.code1 || 0x00,
        code2: keyInfo.code2 || 0x00,
        code3: keyInfo.code3 || 0x00,
      };
      console.log("keyInfo", keyInfo, "newKey", newKey);

      const updatedMouseKeys = mouseKeys.map((key, index) =>
        index === selKeyIndex ? newKey : key
      );

      setMouseKeys(updatedMouseKeys);
      profile.updateMouseKeys(updatedMouseKeys, profileIndex);
      if (connectedMouse) {
        connectedMouse.setMouseKeys(updatedMouseKeys, profileIndex);
      }
    }
  };

  // 切换显示/隐藏状态
  const toggleGroup = (index: number) => {
    setKeyData((prev) =>
      prev.map((item, i) =>
        i === index ? { ...item, show: !item.show } : item
      )
    );
  };

  return (
    <Box className="h-full">
      <Text className="mb-4 text-sm font-semibold text-gray-500">
        点击系统按键至目标设备按键以进行分配
      </Text>
      <Box
        className="flex flex-col space-y-6 overflow-y-auto"
        sx={{
          height: "calc(100vh)", // 减去头部和其他固定元素的高度
          minHeight: "300px", // 设置最小高度
        }}
      >
        {keyData.map((group, groupIndex) => (
          <Box key={groupIndex} mb={4}>
            <Flex
              p={3}
              borderRadius="lg"
              bg="gray.50"
              cursor="pointer"
              alignItems="center"
              justifyContent="space-between"
              onClick={() => toggleGroup(groupIndex)}
              _hover={{ bg: "gray.100" }}
            >
              <Text fontSize="md" fontWeight="semibold">
                {group.name}
              </Text>
              <IconButton
                size="sm"
                variant="ghost"
                aria-label={group.show ? "收起" : "展开"}
                icon={group.show ? <ChevronUpIcon /> : <ChevronDownIcon />}
              />
            </Flex>

            <Collapse in={group.show}>
              <Box mt={2} pl={4}>
                {group.keycodes.map((key, keyIndex) => (
                  <Flex
                    key={keyIndex}
                    p={2}
                    borderRadius="md"
                    cursor="pointer"
                    alignItems="center"
                    bg={
                      selectedKey === `${groupIndex}-${keyIndex}`
                        ? "blue.50"
                        : "transparent"
                    }
                    _hover={{ bg: "gray.50" }}
                    onClick={() =>
                      handleKeyClick(groupIndex, keyIndex, key.name)
                    }
                  >
                    <Text width="150px" fontWeight="medium">
                      {key.name}
                    </Text>
                    <Text color="white" fontSize="sm">
                      {key.desc}
                    </Text>
                  </Flex>
                ))}
              </Box>
            </Collapse>
          </Box>
        ))}
      </Box>
    </Box>
  );
};

export default MacroKey;
